package cn.fancy.sdk.login;

import java.io.File;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.fancy.sdk.FileUtils;
import cn.fancy.sdk.baseview.DialogView;
import cn.fancy.sdk.common.utils.NetworkImpl;
import cn.fancy.sdk.common.utils.ResUtil;

public class ProtocolView extends Activity implements OnClickListener{
	private static String URL="url";
	private static String TITLE="title";
	
	private static Context staticCon;
	
	private ValueCallback<Uri> mUploadMessage; 
	private final static int FILECHOOSER_RESULTCODE = 1;  
	/**
	 * 标题
	 */
	private TextView titleTv;
	
	/**
	 * 返回键
	 */
	private ImageView backIv;
	WebView webView;
	String url;
	
	private Dialog dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(ResUtil.getLayoutId(ProtocolView.this, "guild_protocol"));

		backIv = (ImageView) this.findViewById(ResUtil.getId(ProtocolView.this, "guild_protocol_back"));
		backIv.setOnClickListener(this);
		
		webView =(WebView)this.findViewById(ResUtil.getId(ProtocolView.this, "guild_protocol_web")); 
		
        Intent intent=this.getIntent();
        url=intent.getStringExtra(URL);
        initView();
        
        dialog=DialogView.showWaitingDialog(ProtocolView.this,new OnCancelListener(){
			@Override
			public void onCancel(DialogInterface dialog) {
				
				ProtocolView.this.finish();
			}
		});
	}
    
	private void initView() {
		
		if (!NetworkImpl.isNetworkConnected(staticCon)) {
			//没有网络
			webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}else{
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		}
		
		webView.getSettings().setAppCacheEnabled(false);
		webView.getSettings().setDatabaseEnabled(false);
		webView.getSettings().setDomStorageEnabled(false);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webView.getSettings().setDefaultTextEncodingName("UTF-8");
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		webView.loadUrl(url);
		
		webView.setWebViewClient(new WebViewClient() {
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {  
	            // 如下方案可在非微信内部WebView的H5页面中调出微信支付
//	            if (url.startsWith("weixin://wap/pay?")) {
//	                Intent intent = new Intent();
//	                intent.setAction(Intent.ACTION_VIEW);
//	                intent.setData(Uri.parse(url));
//	                startActivity(intent);
//	 
//	                return true;
//	            }
	            return super.shouldOverrideUrlLoading(view, url);
	        }
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				DialogView.cancelDialog(dialog);
			}
			
		});
		
		webView.setWebChromeClient(new WebChromeClient(){
			
			// For Android 3.0+
		    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
		        Log.i("UPFILE", "in openFile Uri Callback");
		        if (mUploadMessage != null) {
		            mUploadMessage.onReceiveValue(null);
		        }
		        mUploadMessage = uploadMsg;
		        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		        i.addCategory(Intent.CATEGORY_OPENABLE);
		        i.setType("*/*");
		        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
		    }
		    // For Android 3.0+
		    public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
		    	Log.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType);
		        if (mUploadMessage != null) {
		            mUploadMessage.onReceiveValue(null);
		        }
		        mUploadMessage = uploadMsg;
		        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		        i.addCategory(Intent.CATEGORY_OPENABLE);
		        String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
		        i.setType(type);
		        startActivityForResult(Intent.createChooser(i, "File Chooser"),
		                FILECHOOSER_RESULTCODE);
		    }
		    // For Android 4.1
		    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
		    	Log.i("UPFILE", "in openFile Uri Callback has accept Type" + acceptType + "has capture" + capture);
		        if (mUploadMessage != null) {
		            mUploadMessage.onReceiveValue(null);
		        }
		        mUploadMessage = uploadMsg;
		        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
		        i.addCategory(Intent.CATEGORY_OPENABLE);
		        String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
		        i.setType(type);
		        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
		    }
		//Android 5.0+
		});
		
	}
	@Override
	public void onBackPressed() {
		this.finish();
	}
  
    public static void start(Context context,String url,String title){
    	Intent intent = new Intent();
		intent.putExtra(URL, url);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setClass(context, ProtocolView.class);
		staticCon = context;
		context.startActivity(intent);
    }

 
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result == null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            Log.i("UPFILE", "onActivityResult" + result.toString());
            String path =  FileUtils.getPath(this, result);
            if (TextUtils.isEmpty(path)) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
                return;
            }
            Uri uri = Uri.fromFile(new File(path));
            Log.i("UPFILE", "onActivityResult after parser uri:" + uri.toString());
            mUploadMessage.onReceiveValue(uri);
            mUploadMessage = null;
        }
    }
    
	@Override
	public void onClick(View v) {
		if(v.getId() == ResUtil.getId(ProtocolView.this, "guild_protocol_back"))
		{
			this.onBackPressed();
		}
	}
	
  
}
